package com.example.smartcity.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.example.smartcity.R;
import com.example.smartcity.bean.ResponseBean;
import com.example.smartcity.bean.ServiceBean;
import com.example.smartcity.bean.UserBean;
import com.example.smartcity.utils.APIConfig;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.PrivateKey;
import java.util.Arrays;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class UserInfoActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageButton btn_back;
    private ImageView ib_img;
    private EditText et_nicke;
    private EditText et_phone;
    private EditText et_email;
    private EditText et_idetity;
    private RadioButton rb_man;
    private RadioButton rb_woman;
    private RadioGroup rg_sex;
    private Button btn_update;
    private Button btn_clear;
    private String sex = "";
    private static final int REQUEST_CODE = 1; // 请求码

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        initView();
    }

    private void initView()  {
        btn_back = (ImageButton) findViewById(R.id.btn_back);
        ib_img = (ImageView) findViewById(R.id.ib_img);
        et_nicke = (EditText) findViewById(R.id.et_nicke);
        et_phone = (EditText) findViewById(R.id.et_phone);
        et_email = (EditText) findViewById(R.id.et_email);
        et_idetity = (EditText) findViewById(R.id.et_idetity);
        rb_man = (RadioButton) findViewById(R.id.rb_man);
        rb_woman = (RadioButton) findViewById(R.id.rb_woman);
        rg_sex = (RadioGroup) findViewById(R.id.rg_sex);
        btn_update = (Button) findViewById(R.id.btn_update);
        btn_clear = (Button) findViewById(R.id.btn_clear);

        btn_back.setOnClickListener(this);
        btn_update.setOnClickListener(this);
        btn_clear.setOnClickListener(this);
        ib_img.setOnClickListener(this);
        rg_sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (rb_man.isChecked()) {
                    sex = "1";
                } else {
                    sex = "0";
                }
            }
        });
        try{
        getUserInfo();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_update:
                UpdateInfo();
                break;
            case R.id.btn_clear:
                et_nicke.setText("");
                et_phone.setText("");
                et_phone.setText("");
                et_idetity.setText("");
                et_email.setText("");
                sex = "";
                break;
            case R.id.ib_img:
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, REQUEST_CODE);

        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {

            // 处理用户选择的图片
            Uri selectedImageUri = data.getData();
            InputStream imageStream;
            try {
                imageStream = getContentResolver().openInputStream(selectedImageUri);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return;
            }

            // 获取图片名称
            String[] projection = {MediaStore.Images.Media.DISPLAY_NAME};
            String imageName = "";
            Cursor cursor = getContentResolver().query(selectedImageUri, projection, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME);
                imageName = cursor.getString(columnIndex);
                cursor.close();
                Log.d("ImageName", "Selected image name: " + imageName);
            } else {
                Log.d("ImageName", "Failed to get image name");
            }
// 创建用于网络传输的图片数据
            byte[] imageBytes = new byte[0];
            try {
                imageBytes = toByteArray(imageStream);
                Log.i("changedAvatar",imageBytes.toString());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
// 创建HTTP连接并上传图片
            String url = APIConfig.BASE_URL + "/api/upload";
            OkHttpClient client = new OkHttpClient();
            MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
            MediaType mediaType = MediaType.parse("image/jpeg"); // 根据实际情况选择合适的媒体类型
            RequestBody requestBodyImage = RequestBody.create(mediaType, imageBytes);
            Log.i("projectionStr",imageName);
            SharedPreferences sp = this.getSharedPreferences("token_data",MODE_PRIVATE);
            int uid = sp.getInt("token",1);
            builder.addFormDataPart("file",imageName,requestBodyImage);
            builder.addFormDataPart("uid", String.valueOf(uid));
            MultipartBody multipartBody = builder.build();
            Log.i("avatarsend","发送了"+multipartBody.toString());
            Request request = new Request.Builder()
                    .url(url)
                    .post(multipartBody)
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    runOnUiThread(() -> {
                        Toast toast = Toast.makeText(UserInfoActivity.this, "头像修改失败", Toast.LENGTH_SHORT);
                        toast.show();
                    });
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        runOnUiThread(() -> {
                            Glide.with(getApplicationContext()).load(selectedImageUri).into(ib_img);
                            Toast toast = Toast.makeText(UserInfoActivity.this, "头像修改成功", Toast.LENGTH_SHORT);
                            toast.show();
                        });
                    } else {
                        runOnUiThread(() -> {
                            Toast toast = Toast.makeText(UserInfoActivity.this, "头像修改失败", Toast.LENGTH_SHORT);
                            toast.show();
                        });
                    }
                }
            });
            // 在这里可以进行后续的处理，如显示图片等
        }
    }
    private void UpdateInfo() {
        String nicke = et_nicke.getText().toString().trim();
        if (TextUtils.isEmpty(nicke)) {
            Toast.makeText(this, "请输入昵称", Toast.LENGTH_SHORT).show();
            return;
        }
        String phone = et_phone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(this, "请输入你的手机号码", Toast.LENGTH_SHORT).show();
            return;
        }
        String email = et_email.getText().toString().trim();
        if (TextUtils.isEmpty(email)) {
            Toast.makeText(this, "请输入你的邮箱地址", Toast.LENGTH_SHORT).show();
            return;
        }
        String idetity = et_idetity.getText().toString().trim();
        if (TextUtils.isEmpty(idetity)) {
            Toast.makeText(this, "请输入有效的证件信息", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(sex)){
            Toast.makeText(this, "请选择你的性别", Toast.LENGTH_SHORT).show();
            return;
        }
        SharedPreferences sp = this.getSharedPreferences("token_data",MODE_PRIVATE);

        String username = sp.getString("username","");
        int uid = sp.getInt("token",1);
        OkHttpClient client = new OkHttpClient();
        JSONObject object = new JSONObject();
        try {
            object.put("uid",uid);
            object.put("licensenumber",idetity);
            //object.put("username",username);
            object.put("nickname",nicke);
            object.put("phonenumber",phone);
            object.put("email",email);
            object.put("sexual",sex);

        } catch (Exception e) {
            e.printStackTrace();
        }
        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
        RequestBody requestBody = RequestBody.create(mediaType,object.toString());
        Request request = new Request.Builder()
                .url(APIConfig.BASE_URL+"/user/updateuser")
                .post(requestBody)
                .addHeader("Authorization",uid+"")
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("请求失败",e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    Gson gson = new Gson();
                    String result = response.body().string();
                    ResponseBean responseBean = gson.fromJson(result,ResponseBean.class);
                    String code = responseBean.getCode();
                    if (code=="200") {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(),"用户信息修改成功："+result,Toast.LENGTH_LONG).show();;

                            }
                        });
                    }
                }
            }
        });
    }
    private void getUserInfo() throws JSONException {
        SharedPreferences sp = this.getSharedPreferences("token_data",MODE_PRIVATE);
        int uid = sp.getInt("token",1);
        OkHttpClient client = new OkHttpClient();
        JSONObject object = new JSONObject();
        object.put("uid",uid);
        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
        RequestBody requestBody = RequestBody.create(mediaType,object.toString());
        Request request = new Request.Builder()
                .url(APIConfig.BASE_URL+"/user/getuserbyid?uid="+uid)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("请求失败",e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    Gson gson = new Gson();
                    String result = response.body().string();
                    UserBean responseBean = gson.fromJson(result,UserBean.class);
                    if (result!= null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(),"用户信息请求成功："+result,Toast.LENGTH_LONG).show();;
                                Glide.with(getApplicationContext()).load(APIConfig.BASE_URL+responseBean.getAvatarurl()).into(ib_img);
                                et_nicke.setText(responseBean.getNickname());
                                if (responseBean.getPhonenubmber()==null){et_phone.setHint("请输入你的电话号码");
                                    et_phone.setHintTextColor(Color.GRAY);}else{
                                et_phone.setText(responseBean.getPhonenubmber());}
                                if(responseBean.getEmail()!=null){et_email.setText(responseBean.getEmail());}else{
                                    et_email.setHint("请输入你的邮箱");et_email.setHintTextColor(Color.GRAY);}
                                if (responseBean.getLicensenumber()!=null){et_idetity.setText(responseBean.getLicensenumber());}else{
                                    et_idetity.setHint("请输入你的证件号码");et_idetity.setHintTextColor(Color.GRAY);}
                                if(responseBean.getSexual()=="1"){
                                    rb_man.setChecked(true);
                                }else{rb_woman.setChecked(true);}
                            }
                        });
                    }
                }
            }
        });
    }
    private byte[] toByteArray(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        return outputStream.toByteArray();
    }
//    private String getImageavatar(int uid){
//
//    }
}